#!/bin/bash
set -e

# ============================================================
# MiniCPM-V-4_5 NPU 部署脚本
# 对外暴露端口: 18002
# ============================================================

# 配置
IMAGE_NAME="minicpm-v-npu:latest"
CONTAINER_NAME="minicpm-v-api"
CODE_PATH=$(pwd)/MiniCPM-V-4_5
HOST_PORT=18002
CONTAINER_PORT=8000

# 1. 构建镜像
echo "Building Docker image..."
docker build -t "$IMAGE_NAME" -f MiniCPM-V-4_5/Dockerfile MiniCPM-V-4_5/

# 2. 运行容器
echo "Running container..."
# 清理旧容器
docker stop "$CONTAINER_NAME" 2>/dev/null || true
docker rm "$CONTAINER_NAME" 2>/dev/null || true

# 指定使用 NPU 2
NPU_ID=2

# 挂载所有 NPU 设备（驱动初始化需要）
NPU_DEVICE_ARGS=""
for dev in /dev/davinci*; do
    if [ -e "$dev" ]; then
        NPU_DEVICE_ARGS="$NPU_DEVICE_ARGS --device=$dev"
    fi
done
if [ -e "/dev/davinci_manager" ]; then
    NPU_DEVICE_ARGS="$NPU_DEVICE_ARGS --device=/dev/davinci_manager"
fi
if [ -e "/dev/devmm_svm" ]; then
    NPU_DEVICE_ARGS="$NPU_DEVICE_ARGS --device=/dev/devmm_svm"
fi
if [ -e "/dev/hisi_hdc" ]; then
    NPU_DEVICE_ARGS="$NPU_DEVICE_ARGS --device=/dev/hisi_hdc"
fi

# 启动命令
# 挂载 /root/.cache/huggingface 以缓存模型权重
# 挂载宿主机模型目录到容器
MODEL_HOST_PATH="/root/workspace/MiniCPM-V-4_5"

docker run -d \
  --name "$CONTAINER_NAME" \
  --restart=unless-stopped \
  --privileged \
  -p ${HOST_PORT}:${CONTAINER_PORT} \
  $NPU_DEVICE_ARGS \
  -e ASCEND_VISIBLE_DEVICES=$NPU_ID \
  -e ASCEND_RT_VISIBLE_DEVICES=$NPU_ID \
  -e ASCEND_DEVICE_ID=$NPU_ID \
  -v /usr/local/dcmi:/usr/local/dcmi \
  -v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
  -v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
  -v /etc/ascend_install.info:/etc/ascend_install.info \
  -v "$CODE_PATH":/app \
  -v "$MODEL_HOST_PATH":/app/models/MiniCPM-V-4_5 \
  -v $HOME/.cache/huggingface:/root/.cache/huggingface \
  -e MODEL_PATH="/app/models/MiniCPM-V-4_5" \
  "$IMAGE_NAME"

echo ""
echo "============================================================"
echo "Container $CONTAINER_NAME started in background."
echo "API endpoint: http://localhost:${HOST_PORT}/v1/chat/completions"
echo "API docs:     http://localhost:${HOST_PORT}/docs"
echo "============================================================"
echo ""
echo "查看日志:     docker logs -f $CONTAINER_NAME"
echo "停止容器:     docker stop $CONTAINER_NAME"
echo "重启容器:     docker restart $CONTAINER_NAME"
echo ""
echo "最近日志 (最后20行):"
sleep 2
docker logs --tail 20 "$CONTAINER_NAME"


